#include "includes.h"


typedef struct{
	unsigned char cmd;
	unsigned char data1;
	unsigned char data2;
	unsigned char data3;
	unsigned char data4;
}IBUS_DATA;


#define DAC_EN_CONFIG TRISCbits.TRISC0 = 0
#define pRST_CONFIG TRISEbits.TRISE2 = 0
#define pRD_CONFIG TRISEbits.TRISE3 = 0
#define pWR_CONFIG TRISEbits.TRISE4 = 0
#define pCS_CONFIG TRISEbits.TRISE5 = 0
#define pBUS_CLK_CONFIG TRISHbits.TRISH0 = 0

#define DAC_EN PORTCbits.RC0
#define pRST PORTEbits.RE2
#define pRD PORTEbits.RE3  
#define pWR PORTEbits.RE4  
#define pCS PORTEbits.RE5
#define pBUS_CLK	 PORTHbits.RH0

void IbusWrite(IBUS_DATA * ibus_info)
{
    pCS = 0;
    pWR = 0;
    pBUS_CLK = 0;
    
    PORTD = ibus_info->cmd;//tmp&0xFF;//send the first 8 bits data
    Delay1TCY();//delay sometimes for fpga data latch


    pBUS_CLK = !pBUS_CLK;//status machine change to s1
    Delay1TCY();//delay sometimes for fpga data latch

    PORTD = ibus_info->data1;//tmp1;//0x01;
    Delay1TCY();//delay sometimes for fpga data latch


    pBUS_CLK = !pBUS_CLK;
    Delay1TCY();//delay sometimes for fpga data latch
    PORTD = ibus_info->data2;
    Delay1TCY();//delay sometimes for fpga data latch


    pBUS_CLK = !pBUS_CLK;
    Delay1TCY();//delay sometimes for fpga data latch
    PORTD = ibus_info->data3;
    Delay1TCY();//delay sometimes for fpga data latch


    pBUS_CLK = !pBUS_CLK;
    Delay1TCY();//delay sometimes for fpga data latch
    PORTD = ibus_info->data4;
    Delay1TCY();//delay sometimes for fpga data latch

    pBUS_CLK = !pBUS_CLK;//S5
    Delay1TCY();

    pWR = 1;
    pCS = 1;
    Delay1TCY();//delay sometimes for fpga data latch
    pBUS_CLK = 0;
}


void IbusInit(void)
{
    TRISD = 0;
    DAC_EN_CONFIG;
    pRST_CONFIG;
    pRD_CONFIG;
    pWR_CONFIG;
    pCS_CONFIG;
    pBUS_CLK_CONFIG;

    DAC_EN = 1;//disable dac

    pCS = 1;
    pWR = 1;
    pRD = 1;
    pBUS_CLK = 0;


    pRST = 0;
    Delay10KTCYx(10);
    pRST = 1;
}


